package com.ruike.alisurface.ui.payPage;

import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.google.gson.internal.$Gson$Preconditions;
import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.Serials.ReScanUtils;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.bean.ShopDetailBean;
import com.ruike.alisurface.http.OtherHttp;
import com.ruike.alisurface.utils.BackMainUtils;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

import static com.ruike.alisurface.http.OtherHttp.CREATE_PAY_ORDER_BY_PRODUCT_URL;
import static com.ruike.alisurface.http.OtherHttp.CREATE_PAY_ORDER_URL;
import static com.ruike.alisurface.http.OtherHttp.REVERSE_SCAN_PAY_URL;
import static com.ruike.alisurface.http.OtherHttp.SEARCH_ORDER_URL;

/**
 * Author: voodoo
 * CreateDate: 2023/12/27 027下午 03:10
 * Description:
 */
public class PayForReverseScanActivity extends BaseAty implements ReScanUtils.OnReScanListener {

    @BindView(R.id.payForSweep_countDownTime_tv)
    TextView countDownTimeTv;
    @BindView(R.id.payForSweep_state_tv)
    TextView stateTv;

    List<CarGoodsBeans> payCarList;
    private ShopDetailBean shopDetailBean;

    Timer sweepTimer;
    TimerTask sweepTimerTask;

    Timer qrCodeTimer;
    TimerTask qrCodeTimerTask;
    String reScanResultContent; // 反扫出来的数据

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_pay_for_sweep;
    }

    @Override
    protected void initViews() {
        L.i("反扫支付界面==" + this.getClass().getName());
        initTitleBar(false);
    }

    @Override
    protected void initData() {
        payCarList = MyApplication.finalDbUtils.findAll(CarGoodsBeans.class);
        SystemClock.sleep(500);
        if (payCarList == null) {
            L.i("查询商品数据异常");
            showErrorTip("传入的商品数据为空");
            startCountdownTimer(3, null, SelectPayTypeActivity.class);
            return;
        }
        L.i("获取的购物车列表：" + payCarList.toString());
        double payPriceNumber = 0;
        for (CarGoodsBeans carGoodsBean : payCarList) {
            payPriceNumber += carGoodsBean.getPrice();
        }
        L.i("总金额：" + payPriceNumber);
        if (payPriceNumber <= 0) {
            showErrorTip("下单商品不得小于0元");
            startCountdownTimer(3, null, null);
            return;
        }
        ReScanUtils.initListener(); // 初始化反扫器
        ReScanUtils.setOnReScanListener(this); // 设置反扫器回调
        ReScanUtils.stopReadQrCode(); // 停止反扫
        createOrder();
    }

    @Override
    protected void onResume() {
        super.onResume();
        startCountdownTimer(60, countDownTimeTv, SelectPayTypeActivity.class);

    }

    /**
     * 生成二维码提示框
     */
    private void createOrder() {
        try {
            stateTv.setText("正在创建订单，请稍后...");
            showProgressDialog("正创建订单，请稍后......", false);
            if (ShareUtils.getInstance().getInt(ShareKey.IS_SHOP_TYPE, 1) == 1) {
                L.i("按货道展示上传信息");
                getPayinfoCode();
            } else {
                L.i("按商品类型展示上传信息");
                getPayTypeinfoCode();
            }
        } catch (Exception e) {
            L.i("pay====error==", e.getLocalizedMessage());
        }
    }

    /**
     * 按货道下单
     */
    public void getPayinfoCode() {
        OtherHttp.createOrderBySlot(payCarList, this);
    }

    /**
     * 按类型下单
     */
    public void getPayTypeinfoCode() {
        OtherHttp.createOrderByProduct(payCarList, this);
    }

    @OnClick({R.id.payForSweep_goback_imgv})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.payForSweep_goback_imgv:
                startCountdownTimer(0, null, null);
                break;
        }
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        L.i("requestUrl==" + requestUrl);
        if (CREATE_PAY_ORDER_URL.equals(requestUrl) || CREATE_PAY_ORDER_BY_PRODUCT_URL.equals(requestUrl)) {
            try {
                JSONObject resultJSON = new JSONObject(requestJsonStr);
                JSONObject dataJSON = resultJSON.optJSONObject("data");
                if (dataJSON == null) {
                    showErrorTip("创建订单返回的数据为空");
                    startCountdownTimer(3, null, null);
                    return;
                }
                String orderId = dataJSON.optString("id");
                shopDetailBean = new ShopDetailBean(orderId);
                double totalFee = dataJSON.optDouble("total_fee");
                double promotionFee = dataJSON.optDouble("promotion_fee");
                double payFee = dataJSON.optDouble("pay_fee");
                shopDetailBean.setTotal_fee(totalFee);
                shopDetailBean.setPromotion_fee(promotionFee);
                shopDetailBean.setPay_fee(payFee);

                JSONArray detailsArray = dataJSON.optJSONArray("details");
                if (detailsArray == null || detailsArray.length() < 0) {
                    showErrorTip("返回数据出货列表为空");
                    startCountdownTimer(3, null, null);
                    return;
                }
                List<ShopDetailBean.OrderDetailsBean> orderDetailsBeanList = new ArrayList<>();
                for (int i = 0; i < detailsArray.length(); i++) {
                    ShopDetailBean.OrderDetailsBean orderDetailsBean = new ShopDetailBean.OrderDetailsBean();
                    JSONObject detailJSON = (JSONObject) detailsArray.get(i);
                    int slotIndex = detailJSON.optInt("slotIndex");
                    int quantity = detailJSON.optInt("quantity");
                    int slotTypeId = detailJSON.optInt("slotTypeId");
                    orderDetailsBean.setSlotIndex(slotIndex);
                    orderDetailsBean.setQuantity(quantity);
                    orderDetailsBean.setSlotTypeId(slotTypeId);
                    orderDetailsBeanList.add(orderDetailsBean);
                }
                shopDetailBean.setDetailOrderList(orderDetailsBeanList);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            stateTv.setText("订单创建完成，请放置二维码到反扫器前");
            // 提示开始扫码
            ReScanUtils.startReadQrCode(); // 开始反扫

            return;
        }
        // 反扫结果上传返回
        if (REVERSE_SCAN_PAY_URL.equals(requestUrl) || SEARCH_ORDER_URL.equals(requestUrl)) {
            JSONObject object;
            try {
                object = new JSONObject(requestJsonStr);
                int data = object.optInt("data");
//                {"data":0,"code":0,"msg":"success","sendData":"2024-01-05 17:27:40"}
                L.i("getPayResult==" + requestJsonStr);
                if (data == 0) {
                    paySuccessToNext();
                } else {
                    L.i("返回 data = " + data + "，继续轮询");
                    startQrCodeTimer();
                }
            } catch (Exception e) {
                L.e("上报反扫返回结果异常：" + e.toString());
                e.printStackTrace();
            }
        }
    }

    void paySuccessToNext() {
        String order_code = ShareUtils.getInstance().getString(ShareKey.ORDER_RESULT, "");
        L.iTag("支付页==order_code= ", "上次的单号==" + order_code + "==");
        if (!TextUtils.isEmpty(order_code) && shopDetailBean != null && order_code.equals(shopDetailBean.getOrderId())) {
            L.iTag("支付页==order_code= ", "这次的单号=="
                    + shopDetailBean.getOrderId() + "==" + "多次出 货，订单号已经出货过 无法再次出货 回到主页面");
            BackMainUtils.setActivity(this);
            finish();
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString("pay_type", "sweep");
        bundle.putSerializable("orderBeanData", shopDetailBean);
        startActivity(PayShowShopActivity.class, bundle);
        finish();
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        if (CREATE_PAY_ORDER_URL.contentEquals(requestUrl) || REVERSE_SCAN_PAY_URL.contentEquals(requestUrl)) {
            showErrorTip(errorMsg);
            startCountdownTimer(3, null, SelectPayTypeActivity.class);
//            stateTv.setText("正在查询支付信息...");
//            L.e(requestUrl + "==onError=" + errorMsg, "---等待支付--");
//            startQrCodeTimer();
        }
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
    }

    @Override
    public void onReScanResultListener(boolean isSuccess, String content) {
        if (isSuccess) {
            // 反扫到数据之后直接创建订单
            stateTv.setText("识别成功，正在确认信息...");
            showProgressDialog("识别成功（" + content + "），正在上传订单信息");
            reScanResultContent = content;
            OtherHttp.reverseScanPay(this, shopDetailBean.getOrderId(), content);
        } else {
            stateTv.setText(String.format("失败，%s", content));
            restartSweep();
        }
    }

    /**
     * 延时开始扫码
     */
    private void restartSweep() {
        cancelTimer();
        sweepTimer = new Timer();
        sweepTimerTask = new TimerTask() {
            @Override
            public void run() {
                if (!PayForReverseScanActivity.this.isFinishing()) {
                    ReScanUtils.startReadQrCode();
                }
            }
        };
        sweepTimer.schedule(sweepTimerTask, 2_000);
    }

    private void cancelTimer() {
        if (sweepTimer != null) {
            sweepTimer.cancel();
            sweepTimer = null;
        }
        if (sweepTimerTask != null) {
            sweepTimerTask.cancel();
            sweepTimerTask = null;
        }
    }

    void startQrCodeTimer() {
        if (isFinishing()) {
            return;
        }
        cancelQrCodeTimer();
        qrCodeTimer = new Timer();
        qrCodeTimerTask = new TimerTask() {
            @Override
            public void run() {
                OtherHttp.searchOrder(shopDetailBean.getOrderId(), PayForReverseScanActivity.this);
            }
        };
        qrCodeTimer.schedule(qrCodeTimerTask, 3000);
    }

    void cancelQrCodeTimer() {
        if (qrCodeTimer != null) {
            qrCodeTimer.cancel();
            qrCodeTimer = null;
        }
        if (qrCodeTimerTask != null) {
            qrCodeTimerTask.cancel();
            qrCodeTimerTask = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ReScanUtils.stopReadQrCode();
        ReScanUtils.setOnReScanListener(null);
        cancelTimer();
        cancelQrCodeTimer();
    }
}
